package com.dahuyou.netty.binary.img.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import java.net.InetSocketAddress;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

// netty会根据具体的泛型类型来找到合适的inbound消息处理器
//@Slf4j
public class TextWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
 
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
		System.out.println("接收到客户端的消息:[{}]" + msg.text());
		// 如果是向客户端发送文本消息，则需要发送 TextWebSocketFrame 消息
		InetSocketAddress inetSocketAddress = (InetSocketAddress) ctx.channel().remoteAddress();
		String ip = inetSocketAddress.getHostName();
		String txtMsg = "[" + ip + "][" + LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")) + "] ==> " + msg.text();
		ctx.channel().writeAndFlush(new TextWebSocketFrame(txtMsg));
	}
 
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
		System.out.println("服务器发生了异常:" + cause);
	}
 
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
			System.out.println("web socket 握手成功。");
			WebSocketServerProtocolHandler.HandshakeComplete handshakeComplete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
			String requestUri = handshakeComplete.requestUri();
			System.out.println("requestUri:[{}]" + requestUri);
			String subproTocol = handshakeComplete.selectedSubprotocol();
			System.out.println("subproTocol:[{}]" + subproTocol);
			handshakeComplete.requestHeaders().forEach(entry -> System.out.println("header key:[{}] value:[{}]" + entry.getKey() + "---" + entry.getValue()));
		} else {
			super.userEventTriggered(ctx, evt);
		}
	}
}